package com.shijie.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;

import com.shijie.component.ErpUserService;
import com.shijie.core.AbstractService;
import com.shijie.core.ServiceException;
import com.shijie.domain.entity.Admins;
import com.shijie.domain.entity.Brands;
import com.shijie.domain.entity.Products;
import com.shijie.mapper.BrandsMapper;
import com.shijie.mapper.ProductsMapper;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class BrandsService extends AbstractService<Brands> {

	@Resource
	private BrandsMapper brandsMapper;
	@Resource
	private ErpUserService erpUserService;
	@Resource
	private ProductsMapper  productsMapper;

	public List<Brands> list(String q, Integer status) {
		Example condition = new Example(Brands.class);
		Example.Criteria criteria = condition.createCriteria();
		if (status != null) {
			criteria.andEqualTo("status", status);
		}
		if (StringUtils.isNotBlank(q)) {
			criteria.andLike("name", "%" + q + "%");
		}
		Admins admin = erpUserService.getAdmin();
		if(admin != null && admin.getBrandId() != null){
			criteria.andEqualTo("id", admin.getBrandId());
		}
		condition.orderBy("nameEn");
		return brandsMapper.selectByCondition(condition);
	}
	

	public void save(Brands brand){
		if(brand.getId() == null){
			brand.setCreateBy(erpUserService.getUserName());
			brand.setCreateTime(DateTime.now().toDate());
			brandsMapper.insert(brand);
		}else{
			brand.setUpdateBy(erpUserService.getUserName());
			brand.setUpdateTime(DateTime.now().toDate());
			brandsMapper.updateByPrimaryKey(brand);
		}
	}
	
	public void deleteById(Integer id){
		Products p  = new Products();
		p.setBrandId(id);
		List<Products> products = productsMapper.select(p);
		if(products.size() > 0 ){
			throw new ServiceException("此品牌已关联产品，不能删除！");
		}
		brandsMapper.deleteByPrimaryKey(id);
	}

}
